<template>
  <div style="height: 100%">
    <a-spin :spinning="isTableLoading" wrapperClassName="spinning-container">
      <div class="header-container" ref="headerContainer">
        <page-header :title="l('AuditLogs')"></page-header>
        <a-card :bordered="false">
          <a-form :layout="'vertical'" @submit.prevent="getSearchData">
            <a-row :gutter="8">
              <!-- 用户名 -->
              <a-col :sm="24">
                <a-form-item :label="l('UserName')">
                  <a-input-search
                    name="username"
                    :placeholder="l('UserName')"
                    @search="getSearchData"
                    enterButton
                    v-model:value="username"
                  />
                </a-form-item>
              </a-col>
              <!-- 错误状态 -->
              <a-col :sm="12">
                <a-form-item :label="l('ErrorState')">
                  <a-select v-model:value="hasException" @change="getSearchData">
                    <a-select-option value="">{{ l('All') }}</a-select-option>
                    <a-select-option value="false">{{ l('Success') }}</a-select-option>
                    <a-select-option value="true">{{ l('HasError') }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <!--日期范围 -->
              <a-col :sm="12">
                <a-form-item :label="l('DateRange')">
                  <a-range-picker
                    :placeholder="[l('StartDateTime'), l('EndDateTime')]"
                    v-model:value="startToEndDate"
                  />
                </a-form-item>
              </a-col>
              <!-- 服务 -->
              <a-col :sm="12" v-if="advancedFiltersVisible">
                <a-form-item :label="l('Service')">
                  <a-input :placeholder="l('Service')" v-model:value="serviceName" />
                </a-form-item>
              </a-col>
              <!-- 持续时间 -->
              <a-col :sm="12" v-if="advancedFiltersVisible">
                <a-form-item :label="l('Service')">
                  <a-input-number
                    id="MinExecutionDuration"
                    :min="0"
                    :placeholder="l('MinExecutionDuration')"
                    style="text-align: center; width: 152px"
                    :max="86400000"
                    :step="1"
                    v-model:value="minExecutionDuration"
                  />
                  <a-input-number
                    id="MaxExecutionDuration"
                    :min="0"
                    :placeholder="l('MaxExecutionDuration')"
                    style="text-align: center; width: 152px"
                    :max="86400000"
                    :step="1"
                    v-model:value="maxExecutionDuration"
                  />
                </a-form-item>
              </a-col>
              <!-- 方法名 -->
              <a-col :sm="12" v-if="advancedFiltersVisible">
                <a-form-item :label="l('MethodName')">
                  <a-input :placeholder="l('MethodName')" v-model:value="methodName" />
                </a-form-item>
              </a-col>
              <!-- 浏览器 -->
              <a-col :sm="12" v-if="advancedFiltersVisible">
                <a-form-item :label="l('Browser')">
                  <a-input :placeholder="l('Browser')" v-model:value="browserInfo" />
                </a-form-item>
              </a-col>
              <!-- -->
            </a-row>
          </a-form>
          <!-- 操作部分 -->
          <a-row :gutter="8">
            <a-col :md="20" :sm="12"> </a-col>
            <!-- 显示高级过滤 -->
            <a-col :md="4" :sm="12" :offset="20" class="text-right">
              <a @click="advancedFiltersVisible = !advancedFiltersVisible">
                {{ advancedFiltersVisible ? l('HideAdvancedFilters') : l('ShowAdvancedFilters') }}
                <filter-outlined />
              </a>
            </a-col>
          </a-row>
        </a-card>
      </div>
      <!-- table -->
      <!-- 表格 -->
      <div class="table-container">
        <a-table
          size="middle"
          :scroll="{ x: tableWidthScroll, y: tableHeightScroll }"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data-source="dataList"
          :pagination="{
            total: totalItems,
            current: pageNumber,
            pageSize: pageSize,
            showTotal: showTotalInfo,
            showQuickJumper: true,
            showSizeChanger: true,
            change: pageNumberChange,
            showSizeChange: pageNumberChange,
            pageSizeOptions: pageSizeOptions,
            size: 'middle',
          }"
          @change="tableChange"
        >
          <template #bodyCell="{ column, record }">
            <!-- 异常 -->
            <template v-if="column.key === 'exceptionType'">
              <CheckCircleTwoTone v-if="!record.exception" />
              <ExclamationCircleTwoTone v-if="record.exception" twoToneColor="#ff0000" />
            </template>
            <!-- 持续时间 -->
            <template v-if="column.key === 'executionTime'">
              {{ _moment(record.executionTime) }}
            </template>

            <template v-if="column.key === 'actions'">
              <!-- 查看详情 -->
              <div class="detail">
                <a class="table-edit" @click="getDetails(record)">
                  <SecurityScanTwoTone />{{ l('ViewDetails') }}
                </a>
              </div>
            </template>
            <!-- 异常 -->
          </template>
        </a-table>
      </div>
    </a-spin></div
  >
</template>

<script lang="ts">
  import { PagedListingComponentBase, IPagedRequestDto } from '/@/shared/component-base';
  import AuditLogsDetails from './audit-logs-detail/audit-logs-detail.vue';
  import { defineComponent } from 'vue';
  import { AuditLogListDto, AuditLogServiceProxy } from '/@/shared/service-proxies/service-proxies';
  import {
    CheckCircleTwoTone,
    ExclamationCircleTwoTone,
    SecurityScanTwoTone,
    FilterOutlined,
  } from '@ant-design/icons-vue';
  import { ColumnType } from 'ant-design-vue/lib/table';

  export default defineComponent({
    name: 'audit-logs',
    components: {
      AuditLogsDetails,
      CheckCircleTwoTone,
      ExclamationCircleTwoTone,
      SecurityScanTwoTone,
      FilterOutlined,
    },
    mixins: [PagedListingComponentBase],
    data() {
      const minExecutionDuration: number | null | undefined = null;
      const maxExecutionDuration: number | null | undefined = null;
      return {
        // 是否显示高级过滤
        advancedFiltersVisible: false,
        // 用户名
        username: '',
        // 错误状态
        hasException: false,
        // 日期范围
        startToEndDate: [],
        // 服务
        serviceName: '',
        // 持续时间
        minExecutionDuration: minExecutionDuration,
        maxExecutionDuration: maxExecutionDuration,
        // 方法名
        methodName: '',
        // 浏览器
        browserInfo: '',
        _auditLogServiceProxy: new AuditLogServiceProxy(),
      };
    },
    methods: {
      /**
       * 获取数据
       */
      fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
        this._auditLogServiceProxy
          .getPagedAuditLogs(
            this.startToEndDate === null ? undefined : this.startToEndDate[0],
            this.startToEndDate === null ? undefined : this.startToEndDate[1],
            this.username,
            this.serviceName,
            this.methodName,
            this.browserInfo,
            this.hasException,
            this.minExecutionDuration,
            this.maxExecutionDuration,
            request.sorting,
            request.maxResultCount,
            request.skipCount,
          )
          .finally(() => {
            finishedCallback!();
          })
          .then((res) => {
            this.showPaging(res);
          });
      },
      getColumns(): ColumnType<AuditLogListDto>[] {
        return [
          {
            title: 'No',
            customRender: ({ index }) => {
              const a = (this.pageNumber - 1) * this.pageSize + (index + 1);
              return a;
            },
            width: 60,
            fixed: 'left',
          },
          {
            title: this.l('Time'),
            dataIndex: 'executionTime',
            sorter: {
              multiple: 0,
            },
            key: 'executionTime',
            ellipsis: true,
          },
          {
            title: this.l('UserName'),
            dataIndex: 'userName',
            ellipsis: true,
            key: 'userName',
          },
          {
            title: this.l('Service'),
            dataIndex: 'serviceName',
            ellipsis: true,
            key: 'serviceName',
          },
          {
            title: this.l('Action'),
            dataIndex: 'methodName',
            ellipsis: true,
            key: 'methodName',
          },
          {
            title: this.l('Duration'),
            dataIndex: 'executionDuration',
            sorter: {
              multiple: 0,
            },
            ellipsis: true,
            key: 'executionDuration',
          },
          {
            title: this.l('IpAddress'),
            dataIndex: 'clientIpAddress',
            ellipsis: true,
            key: 'clientIpAddress',
          },
          {
            title: this.l('Client'),
            dataIndex: 'clientName',
            ellipsis: true,
            key: 'clientName',
          },
          {
            title: this.l('Browser'),
            dataIndex: 'browserInfo',
            ellipsis: true,
            key: 'browserInfo',
          },
          {
            title: this.l('ExceptionType'),
            dataIndex: 'exceptionType',
            ellipsis: true,
            key: 'exceptionType',
            align: 'center',
          },
          {
            title: this.l('Actions'),
            dataIndex: 'actions',
            fixed: 'right',
            align: 'center',
            width: 250,
            ellipsis: true,
            key: 'actions',
          },
        ];
      },

      /**
       * 查看详情
       */
      getDetails(item: any): void {
        this.modalHelper.create(AuditLogsDetails, { auditLog: item }).subscribe((res) => {
          if (res) {
            this.refresh();
          }
        });
      },
    },
  });
</script>

<style scoped lang="less">
  .subscriptionEndUtc {
    text-align: center;
  }
  .list-table {
    width: 100%;
    white-space: nowrap;
  }
  // table
  .modal-body {
    padding: 0;
    min-width: 100%;
  }

  :deep(.ant-table-tbody > tr > td) {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    &:last-child {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: inherit;
    }
  }

  .table-edit {
    .anticon {
      margin-right: 10px;
    }
  }
  .detail {
    white-space: nowrap;
  }

  .table-delete,
  .ant-dropdown-link {
    margin-left: 20px;
  }

  .table--container {
    margin-top: 20px;
  }
</style>
